class Cpanel::MachinesController < Cpanel::BaseController
  before_action :set_machine, only: [:show, :edit, :update, :destroy]

  def index
    respond_to do |format|
      format.html
      format.json { render json: MachinesDatatable.new(view_context, current_admin) }
    end
  end

  def show; end

  def new
    @machine = Machine.new
  end

  def edit; end

  def create
    @machine = Machine.new(machine_params)

    respond_to do |format|
      if @machine.save
        format.html { redirect_to cpanel_machine_path(@machine), notice: 'Machine was successfully created.' }
        format.json { render :show, status: :created, location: @machine }
      else
        format.html { render :new }
        format.json { render json: @machine.errors, status: :unprocessable_entity }
      end
    end
  end

  def update
    respond_to do |format|
      if @machine.update(machine_params)
        format.html { redirect_to cpanel_machine_path(@machine), notice: 'Machine was successfully updated.' }
        format.json { render :show, status: :ok, location: @machine }
      else
        format.html { render :edit }
        format.json { render json: @machine.errors, status: :unprocessable_entity }
      end
    end
  end

  def destroy
    @machine.destroy
    render js: 'CPANEL.Machines.DataTable.refresh();CPANEL.alert_success("删除成功");'
  end

  def modal
    respond_to do |format|
      format.html
      format.json { render json: MachinesModalDatatable.new(view_context, current_admin) }
    end
  end

  private

  def set_machine
    @machine = Machine.find(params[:id])
  end

  def machine_params
    params.require(:machine).permit(:code, :name, :location, :position, :cell_num, :memo)
  end
end
